﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;


using PMS.BusinessFacade;
using PMS.EntityManage;
using PMS.Common;
using PMS.EntityQuery;
using System.Data.SqlClient;
using System.Collections.Generic;

using BusinessFacade;
using EntityManage;


public partial class Modules_Personal_EvaluateUpdate : System.Web.UI.Page
{
    IPerf_Personal_EvaluateHandler evaluateHandler = new Perf_Personal_EvaluateManage();
    IPerf_Personal_EvaluateDtlHandler evaluateDtlHandler = new Perf_Personal_EvaluateDtlManage();

    ISys_OrganizationHandler organizationHandler = new Sys_OrganizationManage();

    IPerf_Personal_TargetOwnerHandler targetOwnerHandler = new Perf_Personal_TargetOwnerManage();
    DataBase db = new DataBase();

    ISys_UserHandlerExt userHandlerExt = new Sys_UserManageExt();
    IPerf_Personal_EvaluateHandlerExt evaluateHandlerExt = new Perf_Personal_EvaluateManageExt();
    IPerf_Personal_FinalAssignHandler finalAssignHandler = new Perf_Personal_FinalAssignManage();

    static string s_targetID = string.Empty;

    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            DetailBind();

            if (Request["ID"] != null && Request["ID"] != string.Empty)
            {
                Perf_Personal_EvaluateQuery qEvaluate = evaluateHandler.GetPerf_Personal_EvaluateQuery(int.Parse(Request["ID"]));

                if (qEvaluate != null)
                {
                    if ((!CheckPurviews()) || qEvaluate.Status.ToString() != Enums.PEvaluateStatus.AddNew.ToString("d"))
                    {
                        //设置是否可以修改
                        // btnSave.Enabled = false;

                        foreach (GridViewRow row in gvTarget.Rows)
                        {
                            //  TextBox txtEvaluate = (TextBox)row.FindControl("txtScore");
                            TextBox txtRemark = (TextBox)row.FindControl("txtRemark");

                            LinkButton lbtnInput = (LinkButton)row.FindControl("ibtnInput");
                            HtmlInputText txtDate = (HtmlInputText)row.FindControl("txtDate");
                            txtDate.Disabled = false;
                            //txtEvaluate.Enabled = false;
                            txtRemark.Enabled = false;
                        }
                    }
                }
            }
        }

    }

    private bool CheckPurviews()
    {
        if (Session["UserPurviews"] != null)
        {
            string strPur = Session["UserPurviews"].ToString();
            if (strPur.Contains("303012"))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }

    #region Detail

    public string GetUserName(object id)
    {
        return userHandlerExt.GetUserNameByID(int.Parse(id.ToString()));
    }

    public string GetTargetOwner(object id)
    {
        string name = string.Empty;
        Perf_Personal_TargetOwnerQuery query = targetOwnerHandler.GetPerf_Personal_TargetOwnerQuery(int.Parse(id.ToString()));
        if (query != null)
        {
            name = query.Name;
        }
        return name;
    }

    /// <summary>
    /// 获取评分发生次数
    /// </summary>
    /// <param name="targetID"></param>
    /// <returns></returns>
    public string GetNum(object targetID)
    {
        int counter = 0;
        int evaluateID = 0;

        string sqlStr = @"select count(*) as counter from Perf_Personal_EvaluateDtl where Target_ID=@Target_ID and Evaluate_ID=@Evaluate_ID";
        DataTable dt = db.RunSqlTab(sqlStr, new SqlParameter[] { new SqlParameter("@Target_ID", targetID.ToString()), new SqlParameter("@Evaluate_ID", Request["ID"]) });

        if (dt != null && dt.Rows.Count > 0)
        {
            int.TryParse(dt.Rows[0]["counter"].ToString(), out counter);
        }
        return counter.ToString();

    }

    private void DetailBind()
    {
        if (Request["ID"] != null)
        {

            Perf_Personal_EvaluateQuery qEvaluate = evaluateHandler.GetPerf_Personal_EvaluateQuery(int.Parse(Request["ID"]));

            if (qEvaluate != null)
            {

                Perf_Personal_FinalAssignQuery query = finalAssignHandler.GetPerf_Personal_FinalAssignQuery(qEvaluate.Final_Assign_ID);
                if (query != null)
                {

                    txtUser.Text = GetUserName(qEvaluate.Target_User_ID);

                    string sqlStr = @"select FD.Target_ID,T.Name,T.Score from Perf_Personal_FinalAssignDtl FD inner join Perf_Personal_Target T 
                        on FD.Target_ID=T.ID where Final_Assign_ID=@Final_Assign_ID";
                    DataTable dtCounter = db.RunSqlTab(sqlStr, new SqlParameter[] { new SqlParameter("@Final_Assign_ID", query.ID.ToString()) });
                    DataTable dt = db.GetDataTableByIndex(sqlStr, new SqlParameter[] { new SqlParameter("@Final_Assign_ID", query.ID.ToString()) }, AspNetPager2.StartRecordIndex - 1, AspNetPager2.PageSize);
                    if (dtCounter != null && dtCounter.Rows.Count > 0)
                    {
                        AspNetPager2.RecordCount = dtCounter.Rows.Count;
                    }

                    gvTarget.DataSource = dt;
                    gvTarget.DataBind();

                    ////评分详细
                    //Perf_Personal_EvaluateDtlQuery[] detailQuery = evaluateDtlHandler.GetPerf_Personal_EvaluateDtlQueryList("Evaluate_ID=@EvaluateID", new SqlParameter[] { new SqlParameter("@EvaluateID", Request["ID"]) });

                    //if (detailQuery != null && detailQuery.Length > 0)
                    //{
                    //    foreach (GridViewRow row in gvTarget.Rows)
                    //    {
                    //        TextBox txtEvaluate = (TextBox)row.FindControl("txtScore");
                    //        TextBox txtRemark = (TextBox)row.FindControl("txtRemark");
                    //        HiddenField HidTargetID = (HiddenField)row.FindControl("HidTargetID");
                    //        foreach (Perf_Personal_EvaluateDtlQuery q in detailQuery)
                    //        {
                    //            if (HidTargetID.Value == q.Target_ID.ToString())
                    //            {
                    //                txtEvaluate.Text = q.Score.ToString();
                    //                txtRemark.Text = q.Remark;
                    //                break;
                    //            }
                    //        }
                    //    }
                    //}
                }
            }
        }
    }


    protected void gvTarget_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "input")
        {
            try
            {


                Perf_Personal_EvaluateDtlQuery Querys = new Perf_Personal_EvaluateDtlQuery();
                if (gvTarget != null && gvTarget.Rows.Count > 0)
                {

                    foreach (GridViewRow row in gvTarget.Rows)
                    {
                        TextBox txtRemark = (TextBox)row.FindControl("txtRemark");
                        HiddenField HidTargetID = (HiddenField)row.FindControl("HidTargetID");
                        HtmlInputText txtDate = (HtmlInputText)row.FindControl("txtDate");
                        TextBox txtScore = (TextBox)row.FindControl("txtScore");
                        if (HidTargetID.Value == e.CommandArgument.ToString())
                        {
                            Perf_Personal_EvaluateDtlQuery dtlQ = new Perf_Personal_EvaluateDtlQuery();

                            //int iEvaluate = 0;
                            //if (!int.TryParse(txtEvaluate.Text.Trim(), out iEvaluate) || iEvaluate < 0)
                            //{
                            //    Jscript.Alert("分数不能为整数!", this);
                            //    return;
                            //}
                            double score = 0;
                            double.TryParse(txtScore.Text, out score);
                            dtlQ.Target_ID = int.Parse(HidTargetID.Value);
                            dtlQ.Score = score;
                            dtlQ.Remark = txtRemark.Text;
                            dtlQ.Evaluate_ID = int.Parse(Request["ID"]);
                            dtlQ.InsertTime = DateTime.Parse(txtDate.Value);
                            dtlQ.User_ID = int.Parse(Session["CurrentUserID"].ToString());
                            evaluateDtlHandler.InsertPerf_Personal_EvaluateDtl(dtlQ);
                            break;
                        }

                    }
                }


                DetailBind();
                Jscript.AlertInAjax("操作成功!", UpdatePanel2);
            }
            catch { Jscript.AlertInAjax("操作失败!", UpdatePanel2); }


        }

        else if (e.CommandName == "his")
        {
            s_targetID = e.CommandArgument.ToString();
            dataHis(s_targetID);
        }
    }

    protected void gvTarget_RowDataBound(object sender, GridViewRowEventArgs e)
    {
    }

    protected void gvTarget_Sorting(object sender, GridViewSortEventArgs e)
    {
    }

    protected void AspNetPager2_PageChanged(object src, EventArgs e)
    {
        DetailBind();

    }

    private void dataHis(string targetID)
    {

        divHis.Style.Add("display", "block");
        gvHis.DataSource = null;

        string sqlStr = @"select t.Name,t.Score,edtl.Evaluate_ID, edtl.User_ID,edtl.Target_ID,edtl.InsertTime,edtl.Remark
from Perf_Personal_EvaluateDtl edtl 
inner join Perf_Personal_Target t on t.ID=edtl.Target_ID where Target_ID=@Target_ID and Evaluate_ID=@Evaluate_ID";
        DataTable dtCounter = db.RunSqlTab(sqlStr, new SqlParameter[] { new SqlParameter("@Target_ID", s_targetID), new SqlParameter("@Evaluate_ID", Request["ID"]) });
        DataTable dt = db.GetDataTableByIndex(sqlStr, new SqlParameter[] { new SqlParameter("@Target_ID", s_targetID), new SqlParameter("@Evaluate_ID", Request["ID"]) }, AspNetPagerHis.StartRecordIndex - 1, AspNetPagerHis.PageSize);
        if (dtCounter != null && dtCounter.Rows.Count > 0)
        {
            AspNetPagerHis.RecordCount = dtCounter.Rows.Count;
        }

        gvHis.DataSource = dt;
        gvHis.DataBind();

    }

    protected void AspNetPagerHis_PageChanged(object src, EventArgs e)
    {
        dataHis(s_targetID);

    }



    #endregion

    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            if (Request["ID"] != string.Empty)
            {
                Perf_Personal_EvaluateQuery qEvaluate = evaluateHandler.GetPerf_Personal_EvaluateQuery(int.Parse(Request["ID"]));

                if (qEvaluate != null)
                {
                    //先把之前的评分删除再添加新的评分
                    evaluateDtlHandler.DeletePerf_Personal_EvaluateDtl("Evaluate_ID=@Evaluate_ID", new SqlParameter[] { new SqlParameter("@Evaluate_ID", Request["ID"]) });

                    //添加新的评分

                    List<Perf_Personal_EvaluateDtlQuery> lstQuerys = new List<Perf_Personal_EvaluateDtlQuery>();
                    if (gvTarget != null && gvTarget.Rows.Count > 0)
                    {

                        foreach (GridViewRow row in gvTarget.Rows)
                        {
                            Perf_Personal_EvaluateDtlQuery dtlQ = new Perf_Personal_EvaluateDtlQuery();

                            TextBox txtEvaluate = (TextBox)row.FindControl("txtScore");
                            TextBox txtRemark = (TextBox)row.FindControl("txtRemark");
                            HiddenField HidTargetID = (HiddenField)row.FindControl("HidTargetID");
                            int iEvaluate = 0;
                            if (!int.TryParse(txtEvaluate.Text.Trim(), out iEvaluate) || iEvaluate < 0)
                            {
                                Jscript.Alert("分数只能为数字!", this);
                                return;
                            }

                            dtlQ.Target_ID = int.Parse(HidTargetID.Value);
                            dtlQ.Score = iEvaluate;
                            dtlQ.Remark = txtRemark.Text;
                            dtlQ.Evaluate_ID = int.Parse(Request["ID"]);
                            lstQuerys.Add(dtlQ);


                        }
                        evaluateDtlHandler.InsertPerf_Personal_EvaluateDtl(lstQuerys.ToArray());
                    }

                }

            }
            Jscript.Alert("操作成功!", this.Page);
            Jscript.ReturnAndClose(this.Page, "true");
        }
        catch { Jscript.Alert("操作失败!", this.Page); }

    }
}
